package org.jeecg.modules.demo.com.kunpeng.controller;

import java.io.File;
import java.io.IOException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.modules.demo.com.kunpeng.Utils.CustomerInformationUtils;
import org.jeecg.modules.demo.com.kunpeng.entity.CustomerInformation;
import org.jeecg.modules.demo.com.kunpeng.entity.dto.OtherContractKeyWordsQueryDTO;
import org.jeecg.modules.demo.com.kunpeng.vo.OtherContractVO;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.com.kunpeng.entity.OtherContractDetail;
import org.jeecg.modules.demo.com.kunpeng.entity.OtherContractCollectionPlan;
import org.jeecg.modules.demo.com.kunpeng.entity.OtherContract;
import org.jeecg.modules.demo.com.kunpeng.vo.OtherContractPage;
import org.jeecg.modules.demo.com.kunpeng.service.IOtherContractService;
import org.jeecg.modules.demo.com.kunpeng.service.IOtherContractDetailService;
import org.jeecg.modules.demo.com.kunpeng.service.IOtherContractCollectionPlanService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;


/**
 * @Description: 其他合同表
 * @Author: jeecg-boot
 * @Date:   2022-12-23
 * @Version: V1.0
 */
@Api(tags="其他合同表")
@RestController
@RequestMapping("/com.kunpeng/otherContract")
@Slf4j
public class OtherContractController {
	@Autowired
	private IOtherContractService otherContractService;
	@Autowired
	private IOtherContractDetailService otherContractDetailService;
	@Autowired
	private IOtherContractCollectionPlanService otherContractCollectionPlanService;
	
	/**
	 * 分页列表查询
	 *
	 * @param otherContract
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "其他合同表-分页列表查询")
	@ApiOperation(value="其他合同表-分页列表查询", notes="其他合同表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<OtherContract>> queryPageList(OtherContract otherContract,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<OtherContract> queryWrapper = QueryGenerator.initQueryWrapper(otherContract, req.getParameterMap());
		Page<OtherContract> page = new Page<OtherContract>(pageNo, pageSize);
		IPage<OtherContract> pageList = otherContractService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param otherContractPage
	 * @return
	 */
	@AutoLog(value = "其他合同表-添加")
	@ApiOperation(value="其他合同表-添加", notes="其他合同表-添加")
    //@RequiresPermissions("com.kunpeng:other_contract:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody OtherContractPage otherContractPage) {
		log.info("开始处理其他合同表添加请求...");
		OtherContract otherContract = new OtherContract();
		BeanUtils.copyProperties(otherContractPage, otherContract);
		CustomerInformation customerInformation= CustomerInformationUtils.assignmentOtherContractCustomerInformation(otherContractPage);
		log.info("其他合同客户信息："+customerInformation.toString());
		otherContractService.saveMain(otherContract, otherContractPage.getOtherContractDetailList(),otherContractPage.getOtherContractCollectionPlanList(),customerInformation);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param otherContractPage
	 * @return
	 */
	@AutoLog(value = "其他合同表-编辑")
	@ApiOperation(value="其他合同表-编辑", notes="其他合同表-编辑")
    //@RequiresPermissions("com.kunpeng:other_contract:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody OtherContractPage otherContractPage) {
		OtherContract otherContract = new OtherContract();
		BeanUtils.copyProperties(otherContractPage, otherContract);
		OtherContract otherContractEntity = otherContractService.getById(otherContract.getId());
		if(otherContractEntity==null) {
			return Result.error("未找到对应数据");
		}
		otherContractService.updateMain(otherContract, otherContractPage.getOtherContractDetailList(),otherContractPage.getOtherContractCollectionPlanList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "其他合同表-通过id删除")
	@ApiOperation(value="其他合同表-通过id删除", notes="其他合同表-通过id删除")
    //@RequiresPermissions("com.kunpeng:other_contract:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		otherContractService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "其他合同表-批量删除")
	@ApiOperation(value="其他合同表-批量删除", notes="其他合同表-批量删除")
    //@RequiresPermissions("com.kunpeng:other_contract:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.otherContractService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "其他合同表-通过id查询")
	@ApiOperation(value="其他合同表-通过id查询", notes="其他合同表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<OtherContract> queryById(@RequestParam(name="id",required=true) String id) {
		OtherContract otherContract = otherContractService.getById(id);
		if(otherContract==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(otherContract);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "其他合同明细通过主表ID查询")
	@ApiOperation(value="其他合同明细主表ID查询", notes="其他合同明细-通主表ID查询")
	@GetMapping(value = "/queryOtherContractDetailByMainId")
	public Result<List<OtherContractDetail>> queryOtherContractDetailListByMainId(@RequestParam(name="id",required=true) String id) {
		List<OtherContractDetail> otherContractDetailList = otherContractDetailService.selectByMainId(id);
		return Result.OK(otherContractDetailList);
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "其他合同收款计划通过主表ID查询")
	@ApiOperation(value="其他合同收款计划主表ID查询", notes="其他合同收款计划-通主表ID查询")
	@GetMapping(value = "/queryOtherContractCollectionPlanByMainId")
	public Result<List<OtherContractCollectionPlan>> queryOtherContractCollectionPlanListByMainId(@RequestParam(name="id",required=true) String id) {
		List<OtherContractCollectionPlan> otherContractCollectionPlanList = otherContractCollectionPlanService.selectByMainId(id);
		return Result.OK(otherContractCollectionPlanList);
	}

    /**
    * 导出excel
    * @param request
    * @param otherContract
    */
    //@RequiresPermissions("com.kunpeng:other_contract:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, OtherContract otherContract) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<OtherContract> queryWrapper = QueryGenerator.initQueryWrapper(otherContract, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
         List<String> selectionList = Arrays.asList(selections.split(","));
         queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<OtherContract> otherContractList = otherContractService.list(queryWrapper);

      // Step.3 组装pageList
      List<OtherContractPage> pageList = new ArrayList<OtherContractPage>();
      for (OtherContract main : otherContractList) {
          OtherContractPage vo = new OtherContractPage();
          BeanUtils.copyProperties(main, vo);
          List<OtherContractDetail> otherContractDetailList = otherContractDetailService.selectByMainId(main.getId());
          vo.setOtherContractDetailList(otherContractDetailList);
          List<OtherContractCollectionPlan> otherContractCollectionPlanList = otherContractCollectionPlanService.selectByMainId(main.getId());
          vo.setOtherContractCollectionPlanList(otherContractCollectionPlanList);
          pageList.add(vo);
      }
      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "其他合同表列表");
      mv.addObject(NormalExcelConstants.CLASS, OtherContractPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("其他合同表数据", "导出人:"+sysUser.getRealname(), "其他合同表"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("com.kunpeng:other_contract:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<OtherContractPage> list = ExcelImportUtil.importExcel(file.getInputStream(), OtherContractPage.class, params);
              for (OtherContractPage page : list) {
                  OtherContract po = new OtherContract();
                  BeanUtils.copyProperties(page, po);
                  CustomerInformation customerInformation=CustomerInformationUtils.assignmentOtherContractCustomerInformation(page);
                  otherContractService.saveMain(po, page.getOtherContractDetailList(),page.getOtherContractCollectionPlanList(),customerInformation);
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

	 /**
	  * 根据关键字查询数据
	  * @param otherContractKeyWordsQueryDTO
	  * @param pageNo
	  * @param pageSize
	  * @return
	  */
	 @ApiOperation(value="其他合同表-根据关键字分页列表查询", notes="其他合同表-根据关键字分页列表查询")
	 @PostMapping(value = "/listByKeyWords")
	 public Result<IPage<OtherContractVO>> listByKeyWords(@RequestBody OtherContractKeyWordsQueryDTO otherContractKeyWordsQueryDTO,
														  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
		 Result<Page<OtherContractVO>> result = new Result<Page<OtherContractVO>>();
		 Page<OtherContractVO> pageList = new Page<OtherContractVO>(pageNo,pageSize);
		 log.info("关键字查询提交参数："+otherContractKeyWordsQueryDTO.toString());
		 pageList = otherContractService.listByKeyWords(pageList,otherContractKeyWordsQueryDTO);//通知公告消息
		 if(pageList.getRecords().size()==0){
			 return Result.error("没有符合条件的数据，请重新输入！");
		 }
		 log.info("查询当前页："+pageList.getCurrent());
		 log.info("查询当前页数量："+pageList.getSize());
		 log.info("查询结果数量："+pageList.getRecords().size());
		 log.info("数据总数："+pageList.getTotal());
		 result.setSuccess(true);
		 result.setResult(pageList);
		 return Result.ok(pageList);
	 }

	 /**
	  * 处理文件上传
	  * @param pic
	  * @return
	  */
	 @ApiOperation(value = "文件上传接口")
	 @PostMapping(value = "/upload")
	 public Result<String> upload(@RequestPart("file")MultipartFile pic){
		 String fileDir="E:/OtherContractFiles";
		 String fileName=pic.getOriginalFilename();
		 String suffix=fileName.substring(fileName.lastIndexOf("."));
		 fileName= UUID.randomUUID()+suffix;
		 //文件夹不存在则创建
		 File dirFile=new File(fileDir);
		 if(!dirFile.exists()){
			 dirFile.mkdirs();
		 }
		 //文件写入磁盘
		 String filePath=fileDir+"/"+fileName;
		 try {
			 pic.transferTo(new File(filePath));
		 } catch (IOException e) {
			 e.getMessage();
		 }
		 //返回文件的路径
		 return Result.ok(filePath);
	 }

}
